<template>
  <div class="smart-workshop">
    <div class="header">
      <div class="header-left"></div>
      <div class="header-center">
        <div class="title-decoration left"></div>
        <div class="title">自动生产线看板</div>
        <div class="title-decoration right"></div>
      </div>
      <div class="header-right">
        <div class="time">{{ currentTime }}</div>
      </div>
    </div>
    
    <div class="dashboard-content">
      <div class="left-section">
        <!-- 一周不良品统计 -->
        <div class="chart-card">
          <div class="card-header">一周不良品统计</div>
          <div ref="weeklyDefectChart" class="chart"></div>
        </div>

        <div class="small-cards">
          <!-- 关键工序 -->
          <div class="chart-card radar-card">
            <div class="card-header">关键工序</div>
            <div ref="processRadarChart" class="chart radar-chart"></div>
          </div>
          
          <!-- 当日生产率评估 -->
          <div class="info-card rate-card">
            <div class="card-header">当日生产率评估</div>
            <div class="production-rate">
              <div class="rate-item">
                <span class="label">实际完成率:</span>
                <span class="value success">{{ actualRate }}%</span>
              </div>
              <div class="rate-item">
                <span class="label">期望完成率:</span>
                <span class="value">{{ expectedRate }}%</span>
              </div>
              <div class="rate-item">
                <span class="label">单件耗时:</span>
                <span class="value" :class="{ warning: isTimeExceeded }">{{ unitTime }}s</span>
              </div>
              <div class="rate-item">
                <span class="label">标准耗时:</span>
                <span class="value">{{ standardTime }}s</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 一周产量均差 -->
        <div class="chart-card">
          <div class="card-header">一周产量均差</div>
          <div ref="weeklyOutputChart" class="chart"></div>
        </div>
      </div>
      <div class="center-section">
        <div class="progress-cards">
          <!-- 订单总体进度 -->
          <div class="chart-card">
            <div class="card-header">订单总体进度</div>
            <div class="chart-container">
              <div ref="totalProgressChart" class="chart"></div>
              <div class="progress-info">
                <div class="info-item">
                  <span class="label">总计划</span>
                  <span class="value">{{ totalPlan }}</span>
                </div>
                <div class="info-item">
                  <span class="label">已经生产</span>
                  <span class="value">{{ produced }}</span>
                </div>
                <div class="info-item">
                  <span class="label">不良品</span>
                  <span class="value">{{ defects }}</span>
                </div>
                <div class="info-item">
                  <span class="label">完成率</span>
                  <span class="value">{{ completionRate }}%</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 订单今日进度 -->
          <div class="chart-card">
            <div class="card-header">订单今日进度</div>
            <div class="chart-container">
              <div ref="todayProgressChart" class="chart"></div>
              <div class="progress-info">
                <div class="info-item">
                  <span class="label">今日计划</span>
                  <span class="value">{{ todayPlan }}</span>
                </div>
                <div class="info-item">
                  <span class="label">已经生产</span>
                  <span class="value">{{ todayProduced }}</span>
                </div>
                <div class="info-item">
                  <span class="label">不良品</span>
                  <span class="value">{{ todayDefects }}</span>
                </div>
                <div class="info-item">
                  <span class="label">良品率</span>
                  <span class="value success">{{ qualityRate }}%</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 近期生产计划列表 -->
        <div class="table-card production-plan">
          <div class="card-header">近期生产计划列表</div>
          <div class="table-container">
            <div class="scroll-container" ref="scrollContainer">
              <el-table 
                :data="tableData" 
                style="width: 100%" 
                :border="true"
                :show-header="true"
              >
                <el-table-column 
                  prop="tickeNumber" 
                  label="订单号" 
                  align="center"
                  width="120"
                ></el-table-column>
                <el-table-column 
                  prop="plan" 
                  label="计划数量" 
                  align="center"
                  width="100"
                ></el-table-column>
                <el-table-column 
                  prop="stateTime" 
                  label="计划开始时间" 
                  align="center"
                  width="160"
                ></el-table-column>
                <el-table-column 
                  prop="endTime" 
                  label="计划结束时间" 
                  align="center"
                  width="160"
                ></el-table-column>
                <el-table-column 
                  prop="ordersState" 
                  label="订单状态" 
                  align="center"
                  width="100"
                >
                  <template #default="scope">
                    <el-tag v-if="scope.row.ordersState == 0" type="success">创建中</el-tag>
                    <el-tag v-else-if="scope.row.ordersState == 1" type="warning">进行中</el-tag>
                    <el-tag v-else type="danger">订单结束</el-tag>
                  </template>
                </el-table-column>
                <el-table-column 
                  prop="produce" 
                  label="完成率" 
                  align="center"
                  width="80"
                ></el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </div>

      <div class="right-section">
        <div class="info-cards">
          <!-- 当前班组 -->
          <div class="info-card team-card">
            <div class="card-header">当前班组</div>
            <div class="team-info">
              <div class="info-row">
                <div class="label">名称</div>
                <div class="value">{{ currentTeam.teamName }}</div>
              </div>
              <div class="info-row">
                <div class="label">人数</div>
                <div class="value">{{ currentTeam.teamNum }}</div>
              </div>
              <div class="info-row">
                <div class="label">负责人</div>
                <div class="value">{{ currentTeam.duty }}</div>
              </div>
              <div class="info-row">
                <div class="label">电话</div>
                <div class="value">{{ currentTeam.phone }}</div>
              </div>
            </div>
          </div>

          <!-- 异常列表 -->
          <div class="info-card exception-card">
            <div class="card-header">异常列表</div>
            <div class="exception-list">
              <el-table :data="exceptions" style="width: 100%" :border="true">
                <el-table-column prop="type" label="类型" align="center" width="80px"></el-table-column>
                <el-table-column prop="description" label="描述" align="left"></el-table-column>
                <el-table-column prop="time" label="时间" align="center"></el-table-column>
              </el-table>
            </div>
          </div>
        </div>

        <!-- 最近生产产品列表 -->
        <div class="table-card">
          <div class="card-header">最近生产产品列表</div>
          <el-table :data="recentProducts" style="width: 100%" :border="true">
            <el-table-column prop="productSequence" label="产品序列号" align="center"></el-table-column>
            <el-table-column prop="quality" label="产品品质" align="center"></el-table-column>
            <el-table-column prop="produceDate" label="生产时间" align="center"></el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, nextTick } from 'vue'
import * as echarts from 'echarts'
import http from '@/api/http'

// 图表实例
const weeklyDefectChart = ref(null)
const processRadarChart = ref(null)
const weeklyOutputChart = ref(null)
const totalProgressChart = ref(null)
const todayProgressChart = ref(null)

// 数据
const currentTime = ref('')
const totalPlan = ref(0)
const produced = ref(0)
const defects = ref(0)
const completionRate = ref(0)
const todayPlan = ref(0)
const todayProduced = ref(0)
const todayDefects = ref(0)
const qualityRate = ref(0)

// 保存所有进度数据，用于轮播
const allProgressData = ref([]);

//班组
const currentTeamlist = ref([])
const getCurrentTeam = () => {
    http.get('/api/SmartLargeScreen/GetTeamledger').then(res => {
        currentTeamlist.value = res.data
    }).catch(err => {
        console.error('获取班组信息失败:', err)
    })
}

// 计算属性保持不变
const currentTeam = computed(() => {
    return currentTeamlist.value[0] || {
        teamName: '',
        teamNum: 0,
        duty: '',
        phone: ''
    }
})

onMounted(() => {
    getCurrentTeam()
    getProgressData()
    getProductionPlans()
    
})

//获取近期生产计划列表
const productionPlans = ref([])
const getProductionPlans = async () => {
  try {
    // Assuming an API endpoint like /api/Operation/GetTicketLedger
    const res = await http.get('/api/Operation/GetTicketLedger')
    productionPlans.value = res.data

    // 更新总体进度和今日进度 (based on the first '进行中' or '创建中' plan)
    if (productionPlans.value.length > 0) {
      const latestPlan = productionPlans.value.find(plan => plan.state === 1 || plan.state === 0) || productionPlans.value[0]
      console.log('Latest Plan Data from GetTicketLedger:', latestPlan);

      console.log('After getProductionPlans update - productionPlans:', productionPlans.value);
    }
  } catch (err) {
    console.error('获取生产计划失败:', err)
  }
}




// Create duplicated data for seamless loop
const loopedProductionPlans = computed(() => {
  if (productionPlans.value.length === 0) return []
  // Duplicate enough items to fill the visible area at least once, plus a few extra for buffer
  const visibleItemsEstimate = Math.ceil( (scrollContainer.value ? scrollContainer.value.clientHeight : 300) / (singleItemHeight || 50) );
  const itemsToDuplicate = Math.max(productionPlans.value.length, visibleItemsEstimate + 5); 
  return [...productionPlans.value, ...productionPlans.value.slice(0, itemsToDuplicate)]
})

// 优化表格渲染 - now uses loopedProductionPlans
const tableData = computed(() => {
  return loopedProductionPlans.value.map(plan => ({
    ...plan,
    completion: plan.state === 2 ? '100%' : 
               plan.state === 1 ? `${plan.plannedquantity > 0 ? Math.round((plan.produced || 0) / plan.plannedquantity * 100) : 0}%` : '0%'
  }))
})

// 生产率评估数据
const actualRate = ref(10)
const expectedRate = ref(20)
const unitTime = ref(32)
const standardTime = ref(30)
const isTimeExceeded = computed(() => unitTime.value > standardTime.value)

// 最近生产产品数据
const recentProducts = ref([])
const getRecentProducts = async () => {
  try {
    // Assuming an API endpoint like /api/ProductManagement/GetProductMaintenance
    const res = await http.get('/api/ProductManagement/GetProductMaintenance')
    recentProducts.value = res.data
  } catch (err) {
    console.error('获取最近生产产品失败:', err)
  }
}

// 获取订单总体进度数据
const getProgressData = async () => {
  try {
      console.log('开始获取订单总体进度数据:', new Date().toLocaleString())
      const res = await http.get('/api/SmartLargeScreen/GetDailyPlan')
      if (res?.data && Array.isArray(res.data) && res.data.length > 0) {
        // 保存所有数据
        allProgressData.value = res.data
        console.log('获取到新数据，共', allProgressData.value.length, '条')
        
        // Use the first data item for overall and today's progress
        const firstDataItem = allProgressData.value[0];
        
        totalPlan.value = firstDataItem.yield || 0;
        produced.value = firstDataItem.actual || 0;
        defects.value = firstDataItem.defective || 0;
        completionRate.value = totalPlan.value > 0 ? parseFloat(((produced.value / totalPlan.value) * 100).toFixed(2)) : 0;

        todayPlan.value = firstDataItem.yield || 0; 
        todayProduced.value = firstDataItem.actual || 0;
        todayDefects.value = firstDataItem.defective || 0;
        qualityRate.value = todayProduced.value > 0 ? parseFloat((((todayProduced.value - todayDefects.value) / todayProduced.value) * 100).toFixed(2)) : 0;

        console.log('Updated progress data - totalPlan:', totalPlan.value, 'produced:', produced.value, 'todayPlan:', todayPlan.value, 'todayProduced:', todayProduced.value);

        // 获取到数据后立即更新图表
        updateCharts();
      }
    } catch (error) {
      console.error('获取订单总体进度数据失败:', error)
    }
  }


  
// 异常列表数据
const exceptions = ref([
  { type: '设备', description: 'A生产线故障', time: '2025-06-07 08:30:00' },
  { type: '质量', description: '产品外观异常', time: '2025-06-07 08:45:00' }
])

// 表格列配置
const tableColumns = [
  {
    prop: 'documentcode',
    label: '订单号',
    align: 'center',
    width: '120px'
  },
  {
    prop: 'plannedquantity',
    label: '计划数量',
    align: 'center',
    width: '100px'
  },
  {
    prop: 'plannedtarttime',
    label: '计划开始时间',
    align: 'center',
    width: '160px'
  },
  {
    prop: 'createTime',
    label: '计划结束时间',
    align: 'center',
    width: '160px'
  },
  {
    prop: 'state',
    label: '订单状态',
    align: 'center',
    width: '100px',
    render: (row) => {
      const statusMap = {
        0: { type: 'info', text: '创建中' },
        1: { type: 'warning', text: '进行中' },
        2: { type: 'success', text: '订单结束' }
      }
      const status = statusMap[row.state] || statusMap[0]
      return h(ElTag, { type: status.type }, () => status.text)
    }
  },
  {
    prop: 'completion',
    label: '完成率',
    align: 'center',
    width: '80px'
  }
]

// 时间相关
let timeTimer = null
let pageRefreshTimer = null // Define pageRefreshTimer

// 自动滚动相关
const scrollContainer = ref(null)
let scrollTimer = null
const scrollSpeed = 1 // 每步滚动的像素
const scrollInterval = 50 // 每步滚动的毫秒间隔
const scrollDelayAfterLoop = 500 // 滚动到底部后重置前的延迟毫秒数

let currentScrollTop = 0
let totalScrollHeight = 0
let singleItemHeight = 0

// 计算滚动高度
const calculateScrollHeights = () => {
  nextTick(() => {
    const container = scrollContainer.value
    if (!container) {
      console.warn('Scroll container not found.')
      return
    }

    const scrollContent = container.querySelector('.el-table__body')
    if (!scrollContent) {
      console.warn('Table body content not found.')
      return
    }

    totalScrollHeight = scrollContent.scrollHeight
    const firstRow = container.querySelector('.el-table__row')
    singleItemHeight = firstRow ? firstRow.offsetHeight : 0 // 获取单行高度

    // 只有当内容高度超过容器高度时才启动滚动
    if (totalScrollHeight > container.clientHeight && singleItemHeight > 0) {
      startSmoothScroll()
    } else {
      // 如果没有足够的内容滚动，确保滚动位置在顶部，并停止计时器
      container.scrollTop = 0
      stopSmoothScroll()
      console.log('Not enough content to scroll or heights invalid.')
    }
  })
}

// 开始平滑滚动
const startSmoothScroll = () => {
  if (!scrollContainer.value || totalScrollHeight === 0 || singleItemHeight === 0) {
    console.warn('Cannot start smooth scroll: container/heights invalid.', {totalScrollHeight, singleItemHeight})
    return
  }

  if (scrollTimer) clearInterval(scrollTimer) // 清除现有计时器

  // 计算重置点：当滚动到原数据列表的末尾时，立即重置到顶部复制数据的起始点
  const originalDataHeight = productionPlans.value.length * singleItemHeight
  const resetPoint = originalDataHeight // Reset when we are about to enter the duplicated part visually

  scrollTimer = setInterval(() => {
    currentScrollTop += scrollSpeed
    scrollContainer.value.scrollTop = currentScrollTop

    // 当滚动到达重置点时，立即回到顶部
    if (currentScrollTop >= resetPoint) {
      stopSmoothScroll() // 停止当前动画
      setTimeout(() => {
        currentScrollTop = 0
        scrollContainer.value.scrollTop = currentScrollTop // 立即应用重置
        startSmoothScroll() // 延迟后重新启动
      }, scrollDelayAfterLoop)
    }
  }, scrollInterval)
}

// 停止平滑滚动
const stopSmoothScroll = () => {
  if (scrollTimer) {
    clearInterval(scrollTimer)
    scrollTimer = null
  }
}

// 饼图配置
const pieOption = (produced, total, centerText1, centerText2) => ({
  backgroundColor: 'transparent',
  tooltip: {
    trigger: 'item',
    formatter: '{b}: {c} ({d}%)',
    backgroundColor: 'rgba(0,0,0,0.7)',
    borderColor: '#00e4ff',
    textStyle: { color: '#fff' }
  },
  series: [
    {
      type: 'pie',
      radius: ['70%', '90%'],
      center: ['35%', '50%'],
      avoidLabelOverlap: false,
      label: {
        show: true,
        position: 'center',
        formatter: [
          '{a|' + centerText1 + '}',
          '{b|' + centerText2 + '}'
        ].join('\n'),
        rich: {
          a: {
            color: '#00ff66',
            fontSize: 18,
            fontWeight: 'bold',
            lineHeight: 24
          },
          b: {
            color: '#1e90ff',
            fontSize: 16,
            lineHeight: 20
          }
        }
      },
      labelLine: { show: false },
      data: [
        {
          value: produced,
          name: '已生产',
          itemStyle: { color: '#00ff66' }
        },
        {
          value: total - produced,
          name: '待生产',
          itemStyle: { color: '#184b7a' }
        }
      ]
    }
  ]
})

// 初始化图表
const initCharts = () => {
  // 一周不良品统计
  const defectChart = echarts.init(weeklyDefectChart.value)
  defectChart.setOption({
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0,0,0,0.7)',
      borderColor: '#00e4ff',
      textStyle: { color: '#fff' }
    },
    grid: {
      top: '15%',
      left: '10%',
      right: '5%',
      bottom: '10%'
    },
    xAxis: {
      type: 'category',
      data: ['1', '2', '3', '4', '5', '6'],
      axisLine: { 
        lineStyle: { 
          color: '#fff',
          width: 1
        } 
      },
      axisTick: {
        show: false
      }
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 5,
      interval: 1,
      axisLine: { 
        lineStyle: { 
          color: '#fff',
          width: 1
        } 
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(255,255,255,0.1)'
        }
      },
      axisTick: {
        show: false
      }
    },
    series: [{
      data: [4, 3, 2.5, 2, 4, 0.5],
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 6,
      lineStyle: { 
        color: '#00e4ff',
        width: 2
      },
      itemStyle: {
        color: '#00e4ff'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0,
            color: 'rgba(0,228,255,0.3)'
          }, {
            offset: 1,
            color: 'rgba(0,228,255,0)'
          }]
        }
      }
    }]
  })

  // 关键工序雷达图
  const radarChart = echarts.init(processRadarChart.value)
  radarChart.setOption({
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(0,0,0,0.7)',
      borderColor: '#00e4ff',
      textStyle: { color: '#fff' }
    },
    radar: {
      indicator: [
        { name: '压缩端子', max: 100 },
        { name: '绕线', max: 100 },
        { name: '印时码', max: 100 },
        { name: '点胶', max: 100 },
        { name: '装配', max: 100 }
      ],
      splitLine: {
        lineStyle: {
          color: 'rgba(255,255,255,0.2)'
        }
      },
      axisLine: {
        lineStyle: {
          color: 'rgba(255,255,255,0.2)'
        }
      },
      splitArea: {
        show: true,
        areaStyle: {
          color: ['rgba(0,102,255,0.1)', 'rgba(0,102,255,0.2)']
        }
      },
      name: {
        textStyle: {
          color: '#fff'
        }
      }
    },
    series: [{
      type: 'radar',
      data: [{
        value: [90, 85, 95, 80, 88],
        areaStyle: {
          color: 'rgba(0,255,0,0.3)'
        },
        lineStyle: {
          color: '#00ff00',
          width: 2
        },
        itemStyle: {
          color: '#00ff00'
        }
      }]
    }]
  })

  // 订单总体进度
  const totalProgress = echarts.init(totalProgressChart.value)
    totalProgress.setOption(
      pieOption(
        produced.value,
        totalPlan.value,
        '已生产',
        '待生产'
      )
    )
  
    // 订单今日进度
    const todayProgress = echarts.init(todayProgressChart.value)
    todayProgress.setOption(
      pieOption(
        todayProduced.value,
        todayPlan.value,
        '已生产',
        '待生产'
      )
    )

  // 一周产量均差
  const outputChart = echarts.init(weeklyOutputChart.value)
  outputChart.setOption({
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0,0,0,0.7)',
      borderColor: '#00e4ff',
      textStyle: { color: '#fff' }
    },
    grid: {
      top: '10%',
      left: '10%',
      right: '5%',
      bottom: '15%'
    },
    xAxis: {
      type: 'category',
      data: ['1', '2', '3', '4', '5', '6'],
      axisLine: { 
        lineStyle: { 
          color: '#fff',
          width: 2
        } 
      },
      axisTick: {
        show: false
      }
    },
    yAxis: {
      type: 'value',
      axisLine: { 
        lineStyle: { 
          color: '#fff',
          width: 2
        } 
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(255,255,255,0.1)'
        }
      },
      axisTick: {
        show: false
      }
    },
    series: [{
      data: [1000, 200, 400, 500, 600, 0],
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 8,
      lineStyle: { 
        color: '#00ff00',
        width: 3
      },
      itemStyle: {
        color: '#00ff00'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0,
            color: 'rgba(0,255,0,0.3)'
          }, {
            offset: 1,
            color: 'rgba(0,255,0,0)'
          }]
        }
      }
    }]
  })
}



// 更新所有图表数据
const updateCharts = () => {
  if (totalProgressChart.value) {
    const totalProgress = echarts.getInstanceByDom(totalProgressChart.value)
    if (totalProgress) {
      totalProgress.setOption(pieOption(produced.value, totalPlan.value, '已生产', '待生产'))
    }
  }
  if (todayProgressChart.value) {
    const todayProgress = echarts.getInstanceByDom(todayProgressChart.value)
    if (todayProgress) {
      todayProgress.setOption(pieOption(todayProduced.value, todayPlan.value, '已生产', '待生产'))
    }
  }
}

// 处理窗口大小变化
const handleResize = () => {
  const chartInstances = [
    echarts.getInstanceByDom(weeklyDefectChart.value),
    echarts.getInstanceByDom(processRadarChart.value),
    echarts.getInstanceByDom(weeklyOutputChart.value),
    echarts.getInstanceByDom(totalProgressChart.value),
    echarts.getInstanceByDom(todayProgressChart.value),
  ]
  chartInstances.forEach(chart => {
    chart && chart.resize()
  })
  stopSmoothScroll() // Re-calculate scroll heights after resize
  calculateScrollHeights()
}

// 刷新所有数据的函数
const refreshAllData = async () => {
  try {
    await Promise.all([
      getCurrentTeam(), // This fetches the current team data
      getProductionPlans(), // This fetches production plan data (overall & today's progress)
      getRecentProducts(), // This fetches recent products data
      getProgressData(), // This fetches daily plan data
    ])
    // Update charts after new data is fetched
    updateCharts()
  } catch (err) {
    console.error('刷新数据失败:', err)
  }
}

// 清理所有定时器
const clearAllTimers = () => {
    if (progressTimer) {
      clearInterval(progressTimer)
      progressTimer = null
    }
    if (dataFetchTimer) {
      clearInterval(dataFetchTimer)
      dataFetchTimer = null
    }
  }

  // 启动定时器
  const startTimer = () => {
    // 清理可能存在的旧定时器
    clearAllTimers()
    
    // 重置索引
    currentDataIndex = 0
    
    // 立即执行一次数据获取
    getProgressData().then(() => {
      // 获取到数据后立即显示第一条
      if (allProgressData.value.length > 0) {
        updateDisplayData()
      }
    })
    
    // 设置数据轮换定时器，每5秒切换显示
    progressTimer = setInterval(() => {
      updateDisplayData()
    }, 5000)
    
    // 设置数据获取定时器，每30秒更新一次数据
    dataFetchTimer = setInterval(() => {
      getProgressData()
    }, 30000)
    
    console.log('定时器已启动 - 数据轮换间隔：5秒，数据获取间隔：30秒')
  }

  // 启动生产计划列表定时器
  const startPlanListTimer = () => {
    // 清理可能存在的旧定时器
    if (planListTimer) {
      clearInterval(planListTimer)
      planListTimer = null
    }
    
    // 立即执行一次数据获取
    getProductionPlanList()
    
    // 设置定时器，每5秒更新一次数据
    planListTimer = setInterval(() => {
      getProductionPlanList()
    }, 5000)
    
    console.log('生产计划列表定时器已启动，间隔：5秒')
  }


// 生命周期钩子
onMounted(async () => {
  // 初始化数据
  await refreshAllData()
  
  // 初始化图表
  initCharts()
  
  // 启动时间更新计时器
  timeTimer = setInterval(() => {
    currentTime.value = `${new Date().getFullYear()}年${new Date().getMonth() + 1}月${new Date().getDate()}日-${new Date().getHours()}时${new Date().getMinutes()}分${new Date().getSeconds()}秒`
  }, 1000)

  // 启动数据刷新计时器
  pageRefreshTimer = setInterval(refreshAllData, 5000) // Call refreshAllData every 5 seconds

  // 确保在数据加载完成且 DOM 更新后开始滚动
  nextTick(() => {
    calculateScrollHeights()
  })

  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  stopSmoothScroll() // 停止平滑滚动
  if (timeTimer) clearInterval(timeTimer) // 清除时间更新计时器
  if (pageRefreshTimer) clearInterval(pageRefreshTimer) // Clear page refresh timer
  
  window.removeEventListener('resize', handleResize) // 移除窗口大小监听
  const chartInstances = [
    echarts.getInstanceByDom(weeklyDefectChart.value),
    echarts.getInstanceByDom(processRadarChart.value),
    echarts.getInstanceByDom(weeklyOutputChart.value),
    echarts.getInstanceByDom(totalProgressChart.value),
    echarts.getInstanceByDom(todayProgressChart.value),
  ]
  chartInstances.forEach(chart => {
    chart && chart.dispose() // 销毁 Echarts 实例
  })
})
</script>

<style scoped>
.smart-workshop {
  width: 100%;
  min-height: 100vh;
  background: radial-gradient(ellipse at center, #0a2033 0%, #001529 100%);
  color: white;
  padding: 20px;
  box-sizing: border-box;
  height: 100vh; /* Ensure full viewport height */
}

.header {
  display: grid;
  grid-template-columns: 1fr auto 1fr;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 20px;
  position: relative;
  background: linear-gradient(to right, rgba(0, 102, 255, 0.05), transparent, rgba(0, 102, 255, 0.05));
  border-bottom: 1px solid rgba(0, 102, 255, 0.3);
  box-shadow: 0 2px 10px rgba(0, 102, 255, 0.2);
}

.header-center {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 25px;
}

.title {
  font-size: 38px;
  font-weight: bold;
  color: #fff;
  text-align: center;
  position: relative;
  padding: 5px 30px;
  background: linear-gradient(180deg, #ffffff 0%, #87ceeb 100%); /* Lighter blue for effect */
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-shadow: 0 0 15px rgba(74, 159, 255, 0.7);
  letter-spacing: 2px;
  animation: pulse 2s infinite alternate;
}

@keyframes pulse {
  from { text-shadow: 0 0 10px rgba(74, 159, 255, 0.5), 0 0 20px rgba(74, 159, 255, 0.3); }
  to { text-shadow: 0 0 20px rgba(74, 159, 255, 0.8), 0 0 30px rgba(74, 159, 255, 0.5); }
}

.title-decoration {
  width: 180px;
  height: 3px;
  background: linear-gradient(90deg,
    transparent 0%,
    #00e4ff 50%,
    transparent 100%
  );
  position: relative;
  animation: glowLine 3s infinite ease-in-out;
}

@keyframes glowLine {
  0% { opacity: 0.5; }
  50% { opacity: 1; }
  100% { opacity: 0.5; }
}

.title-decoration::before {
  content: '';
  position: absolute;
  top: -5px;
  width: 12px;
  height: 12px;
  background: #00e4ff;
  transform: rotate(45deg);
  box-shadow: 0 0 10px #00e4ff;
}

.title-decoration.left::before {
  right: 0;
}

.title-decoration.right::before {
  left: 0;
}

.header-right {
  display: flex;
  justify-content: flex-end;
}

.time {
  font-size: 20px;
  color: #fff;
  background: rgba(0, 102, 255, 0.3);
  padding: 8px 20px;
  border-radius: 8px;
  border: 1px solid rgba(74, 159, 255, 0.5);
  box-shadow: 0 0 12px rgba(74, 159, 255, 0.7);
  font-family: 'Share Tech Mono', monospace;
  letter-spacing: 1px;
}

.dashboard-content {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr;
  gap: 20px;
  padding: 0 20px;
  grid-template-rows: auto 1fr; /* Ensures header is auto height, and content fills rest */
  height: calc(100vh - 100px); /* Adjust based on header height, making content fill viewport */
}

.left-section, .right-section, .center-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.chart-card, .info-card, .table-card {
  background: rgba(0, 21, 41, 0.8);
  border: 1px solid rgba(0, 102, 255, 0.5);
  border-radius: 8px;
  margin-bottom: 0px; /* Remove margin-bottom as gap handles spacing */
  overflow: hidden;
  box-shadow: 0 0 15px rgba(0, 102, 255, 0.3), inset 0 0 5px rgba(0, 102, 255, 0.1);
  transition: all 0.3s ease-in-out;
  flex-grow: 1; /* Allow cards to grow within flex containers */
  display: flex; /* Make cards flex containers themselves for inner content */
  flex-direction: column; /* Stack inner content vertically */
}

.chart-card:hover, .info-card:hover, .table-card:hover {
  box-shadow: 0 0 25px rgba(0, 102, 255, 0.6), inset 0 0 8px rgba(0, 102, 255, 0.2);
  transform: translateY(-3px);
}

.card-header {
  background: linear-gradient(90deg, rgba(0, 102, 255, 0.3) 0%, rgba(0, 102, 255, 0) 100%);
  color: #fff;
  padding: 12px 20px;
  font-size: 18px;
  font-weight: bold;
  border-bottom: 1px solid #0066ff;
  text-shadow: 0 0 5px rgba(0, 255, 255, 0.5);
  border-radius: 8px 8px 0 0;
}

.chart {
  height: 80px;
  width: 80px;
  padding: 0;
  flex-shrink: 0;
  margin-bottom: 5px;
  margin-right: 0;
}

.progress-cards {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 0px; /* Remove margin-bottom */
  flex-grow: 1; /* Allow progress cards section to grow */
}

.chart-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 5px;
  flex-grow: 1;
}

.progress-info {
  padding: 10px; /* Adjust padding for the grid container */
  display: grid; /* Use grid for 2x2 layout */
  grid-template-columns: repeat(2, 1fr); /* Two columns */
  gap: 10px; /* Gap between grid items */
  flex-grow: 1;
  width: 100%;
  text-align: left; /* Text alignment within grid items, not centered */
}

.progress-info .info-item {
  display: flex;
  flex-direction: column; /* Stack label and value vertically within each item */
  align-items: flex-start; /* Align text to start */
  padding: 8px 12px; /* Re-add padding */
  background: rgba(0, 102, 255, 0.08); /* Re-add background */
  border-radius: 4px; /* Re-add border radius */
  border-left: 3px solid #00e4ff; /* Re-add left border */
  transition: all 0.3s ease-in-out;
  box-shadow: 0 0 5px rgba(0, 102, 255, 0.2); /* Re-add subtle shadow */
}

.progress-info .info-item:hover {
  background: rgba(0, 102, 255, 0.15);
  box-shadow: 0 0 10px rgba(0, 102, 255, 0.4);
  transform: translateY(-1px);
}

.progress-info .info-item .label {
  color: #a0cfff;
  font-size: 13px; /* Slightly larger label */
  font-weight: normal;
  margin-bottom: 2px; /* Space between label and value */
}

.progress-info .info-item .value {
  color: #fff;
  font-size: 18px; /* Larger font size for values */
  font-weight: bold;
  text-shadow: 0 0 5px rgba(0, 255, 255, 0.3); /* Re-add text shadow for values */
}

.team-info {
  padding: 15px;
  display: flex;
  flex-direction: column;
  gap: 10px; /* Increased gap */
  flex-grow: 1;
  justify-content: flex-start;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 15px;
  background: rgba(0, 102, 255, 0.05);
  border-radius: 4px;
  font-size: 15px;
  border-bottom: 1px solid rgba(0, 102, 255, 0.3);
  margin-bottom: 5px;
  transition: background 0.3s ease, box-shadow 0.3s ease;
}

.info-row:hover {
  background: rgba(0, 102, 255, 0.15);
  box-shadow: 0 0 10px rgba(0, 102, 255, 0.4);
}

.info-row:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.info-row .label {
  color: #a0cfff;
  min-width: 80px;
  font-weight: normal;
}

.info-row .value {
  color: #fff;
  flex: 1;
  font-weight: bold;
  text-align: right;
  padding-left: 10px;
}

.production-rate {
  padding: 10px;
  height: auto; /* Let content define height */
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}

.rate-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  padding: 8px 15px;
  background: rgba(0, 102, 255, 0.05);
  border-radius: 4px;
  border-left: 3px solid #00e4ff;
  transition: background 0.3s ease, box-shadow 0.3s ease;
}

.rate-item:hover {
  background: rgba(0, 102, 255, 0.15);
  box-shadow: 0 0 10px rgba(0, 102, 255, 0.4);
}

.label {
  color: #a0cfff;
  font-weight: normal;
}

.value {
  color: #fff;
  font-weight: bold;
}

.success {
  color: #00ff00;
  text-shadow: 0 0 5px rgba(0, 255, 0, 0.5);
}

.warning {
  color: #ff9900;
  text-shadow: 0 0 5px rgba(255, 153, 0, 0.5);
}

/* El-table specific overrides */
:deep(.el-table) {
  background-color: transparent !important;
  color: white !important;
  font-size: 14px;
}

:deep(.el-table th),
:deep(.el-table tr),
:deep(.el-table td) {
  background-color: transparent !important;
  border-color: rgba(0, 102, 255, 0.3) !important;
  color: white !important;
}

:deep(.el-table thead th) {
  background-color: rgba(0, 102, 255, 0.3) !important;
  color: #e0f2f7 !important;
  font-weight: bold;
  text-shadow: 0 0 3px rgba(0, 255, 255, 0.3);
}

:deep(.el-table--border) {
  border-color: rgba(0, 102, 255, 0.5) !important;
}

/* El-tag specific overrides */
:deep(.el-tag) {
  border: none;
  font-weight: bold;
}

:deep(.el-tag--info) {
  background-color: rgba(144, 147, 153, 0.2);
  color: #a0cfff;
}

:deep(.el-tag--warning) {
  background-color: rgba(230, 162, 60, 0.2);
  color: #ffcc66;
}

:deep(.el-tag--success) {
  background-color: rgba(0, 255, 0, 0.2);
  color: #00ff66;
}

/* Specific layout adjustments for sections and cards */
.small-cards {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  flex-grow: 1;
}

.radar-card, .rate-card {
  height: auto;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}

.radar-chart {
  height: 180px;
}

.exception-card {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  max-height: none; /* Allow content to dictate height */
  margin-top: 0px; /* Ensure no extra margin */
}

.exception-list {
  flex-grow: 1;
  overflow-y: auto;
  padding: 5px;
}

.table-card {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
}

.table-container {
  height: auto;
  max-height: 280px; /* Adjust as needed based on image */
  overflow: hidden;
  position: relative;
  flex-grow: 1;
}

.scroll-container {
  height: 100%;
  overflow-y: auto;
  position: relative;
}

/* Custom scrollbar styles (re-applied for all table wrappers) */
:deep(.el-table__body-wrapper) {
  overflow-y: auto !important;
  scrollbar-width: thin;
  scrollbar-color: rgba(74, 159, 255, 0.5) rgba(9, 30, 66, 0.5);
  background-color: transparent !important; /* Ensure the wrapper itself is transparent */
}

:deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 6px;
  background-color: rgba(0, 21, 41, 0.8); /* Explicitly set scrollbar background */
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
  background: rgba(9, 30, 66, 0.8); /* Darker track background */
  border-radius: 3px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  background: rgba(74, 159, 255, 0.5);
  border-radius: 3px;
  transition: background 0.3s ease;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb:hover) {
  background: rgba(74, 159, 255, 0.8);
}

.table-card.production-plan {
  flex-grow: 1;
}

.table-card.production-plan .table-container {
  max-height: 320px; /* Adjust as needed */
  background-color: rgba(0, 21, 41, 0.8); /* Ensure a dark background for the container */
}

.table-card.production-plan .scroll-container {
  height: 100%;
  background-color: rgba(0, 21, 41, 0.8); /* Ensure a dark background for the scrollable area */
}

.right-section .info-cards {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
  margin-bottom: 0px;
  height: auto; /* Allow content to dictate height */
}

.right-section .info-card {
  margin-bottom: 0;
  display: flex;
  flex-direction: column;
}

/* Specific styles for "当前班组" card */
.team-card {
  max-height: none; /* Allow content to expand fully */
  /* Re-added previously defined styles for consistency */
  background: rgba(0, 21, 41, 0.8);
  border: 1px solid rgba(0, 102, 255, 0.5);
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 0 10px rgba(0, 102, 255, 0.2);
  position: relative;
}

.team-card::before { /* Glowing border effect */
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  border: 1px solid rgba(0, 102, 255, 0.3);
  border-radius: 4px;
  pointer-events: none;
}


.recent-products-card {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}

.recent-products-card .el-table {
  flex-grow: 1;
}

.production-rate {
  height: auto;
  flex-grow: 1;
}
</style>
